package com.mg.demo;

import com.mg.demo.entity.User;
import com.mg.demo.repository.MyMongoRepsitory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;

import java.util.List;

/**
 * @version 1.0
 * @Author: 许啸林
 * @Date: 2021/7/21 12:04
 */
@SpringBootTest
public class RepositoryDemo {
    @Autowired
    MyMongoRepsitory myMongoRepsitory;

    @Test
    public void add() {
        User user = new User();
        user.setAge(33);
        user.setEmail("1241dqq@qq.com");
        user.setName("wz");
        User insertUser = myMongoRepsitory.insert(user);
        System.out.println(insertUser.toString());
    }

    @Test
    public void findAll() {
        List<User> userlist = myMongoRepsitory.findAll();
        userlist.forEach(item -> System.out.println(userlist.toString()));
    }

    @Test
    public void findById() {
        User user = myMongoRepsitory.findById("60f68ef23cc96d69d5413731").get();
        System.out.println(user.toString());
    }

    /**
     * 条件查询
     */
    @Test
    public void findParam() {
        User user = new User();
        user.setAge(33);
        user.setName("wz");
        Example<User> userExample = Example.of(user);
        List<User> userlist = myMongoRepsitory.findAll(userExample);
        userlist.forEach(item -> System.out.println(userlist.toString()));
    }

    /**
     * 模糊查询
     */
    @Test
    public void fuzzyQuery() {
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true);

        User user = new User();
        user.setAge(33);
        user.setName("w");
        Example<User> userExample = Example.of(user, matcher);
        List<User> userlist = myMongoRepsitory.findAll(userExample);
        userlist.forEach(item -> System.out.println(userlist.toString()));
    }

    /**
     * 分页查询
     */
    @Test
    public void findByPage() {
        Sort sort = Sort.by(Sort.Direction.DESC, "age");
        Pageable pageable = PageRequest.of(0,3, sort);
        User user = new User();
        Example<User> userExample = Example.of(user);
        Page<User> page = myMongoRepsitory.findAll(userExample, pageable);
        List<User> content = page.getContent();
        System.out.println("分页条数:" + page.getTotalElements());
        content.forEach(item -> System.out.println(item.toString()));
    }

    @Test
    public void edit() {
        User user = myMongoRepsitory.findById("60f68ef23cc96d69d5413731").get();
        user.setAge(20);
        user.setName("asdwf");
        User save = myMongoRepsitory.save(user);
        System.out.println("根据id修改信息:" + save.toString());
    }

    @Test
    public void remove() {
        myMongoRepsitory.deleteById("60f68ef23cc96d69d5413731");
    }
}
